package cc.loac.heba.controller;

import cc.loac.heba.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class MessageController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    MessageService messageService;

    @GetMapping("/message")
    @ResponseBody
    public String getMessage(@RequestParam("email") String email,
                             HttpServletRequest request) {
        logger.info(email + ": getMessage");
        String token = request.getHeader("admin-token");
        return messageService.getMessage(email, token);
    }

    @DeleteMapping("/message")
    @ResponseBody
    public String deleteMessage(@RequestParam("email") String email,
                                HttpServletRequest request) {
        logger.info(email + ": deleteMessage");
        String token = request.getHeader("admin-token");
        return messageService.removeMessage(email, token);
    }

    @PostMapping("/message/read")
    @ResponseBody
    public String updateMessageRead(@RequestParam("email") String email,
                                    @RequestParam("messageIds") String messageIds,
                                    HttpServletRequest request) {
        logger.info(email + ": updateMessageRead");
        String token = request.getHeader("admin-token");
        List<String> ids = new ArrayList<>(Arrays.asList(messageIds.split(",")));
        return messageService.updateMessageRead(email, ids, token);
    }

    @PostMapping("/message/readAll")
    @ResponseBody
    public String updateAllMessageRead(@RequestParam("email") String email,
                                    HttpServletRequest request) {
        logger.info(email + ": updateMessageRead");
        String token = request.getHeader("admin-token");
        return messageService.updateAllMessageRead(email, token);
    }
}
